import Vue from 'vue'
import Router from 'vue-router'
// import HelloWorld from '@/components/HelloWorld'
import login from '@/views/login.vue'
import homePage from '@/views/homePage.vue'
import Home from '@/views/homePage-Home.vue'
import my404 from '@/views/my404.vue'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'login',
      component: login
    },
    {
      path: '/homePage',
      name: 'homePage',
      component: homePage,
      children: [ // 开始嵌套路由，这下面的所有路由都是homePage路由的子路由
        {
          path: '/', // 嵌套路由里默认是哪个网页
          redirect: 'homePageHome'
        },
        {
          path: '/homePage/Home',
          name: 'Home',
          component: Home,
          meta: {
            title: '首页',
            requireAuth: true// 该路由项需要权限校验
          }
        }
      ]
    },
    {
      path: '/*',
      name: '404',
      component: my404
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
    if (localStorage.token) { // 获取当前的token是否存在
      console.log('token存在')
      next()
    } else {
      console.log('token不存在')
      next({
        path: '/', // 将跳转的路由path作为参数，登录成功后跳转到该路由
        query: {redirect: to.fullPath}
      })
    }
  } else { // 如果不需要权限校验，直接进入路由界面
    next()
  }
})
export default router
